#include "stdafx.h"

#pragma warning(push)
#pragma warning( disable: 4355 )
Game::Game(void) :
	mWnd(*this)
{
}


Game::~Game(void)
{
}


void Game::initialize(int width, int height, const char* title)
{
	mWnd.create(width, height, title);
}


void Game::start()
{
	mWnd.show();

	auto lasTime = timeGetTime();

	D3DXMatrixIdentity(&globals::matIdentity);
	

	while(mWnd.isRunning())
	{
		mWnd.doEvents();
		auto curTime = timeGetTime();
		mElapsedTime = (float)((curTime - lasTime) * 0.001);
		lasTime = curTime;

		globals::d3dDevice->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_COLORVALUE(0.2f, 0.2f, 0.0f, 1.0f), 1.0f, 0);

		globals::d3dDevice->BeginScene();

		onDrawEvent();
		

		globals::d3dDevice->EndScene();
		globals::d3dDevice->Present(nullptr, nullptr, nullptr, nullptr);
	}
}


void Game::setOnDrawEvent(const luabind::object &fn)
{
	if(luabind::type(fn) == LUA_TFUNCTION)
		mOnDrawFunction = fn;
}


void Game::onDrawEvent()
{
	if(mOnDrawFunction.is_valid())
		luabind::call_function<void>(mOnDrawFunction, mElapsedTime);
}


LRESULT Game::doMessage(HWND window, UINT message, WPARAM wParam, LPARAM lParam)
{
/*	switch(message)
	{
	default:*/
		return DefWindowProc(window, message, wParam, lParam);
//	}
}

void Game::showConsole()
{
	AllocConsole();
}


bool Game::isKeyDown(char n)
{
	unsigned char keys[256];
	GetKeyboardState( keys );

	if(::GetFocus() != mWnd.getHandle())
		return false;

	if(n < 256)
		return (keys[n] & 0x80) != 0;
	else
		return false;
}

bool Game::isKeyDown(const std::string& n)
{
	unsigned char keys[256];
	GetKeyboardState( keys );

	if(::GetFocus() != mWnd.getHandle())
		return false;

	if(n.length() >= 1 && n[0] < 256)
		return (keys[n[0]] & 0x80) != 0;
	else
		return false;
}


bool Game::isMouseDown(int btn)
{
	if((btn == VK_LBUTTON || btn == VK_RBUTTON || btn == VK_MBUTTON) && ::GetFocus() == mWnd.getHandle())
		return (GetKeyState(btn) & 0x80) != 0;
	return false;
}


POINT Game::getMousePosition()
{
	POINT p;
	GetCursorPos(&p);
	ScreenToClient( mWnd.getHandle(), &p );
	return p;
}


void Game::stop()
{
	mWnd.close();
}


void Game::toLua()
{
	using luabind::def;
	using luabind::class_;

	luabind::module(lua::State())
	[
		class_<Game>("CGame").
		//def(luabind::constructor<>()).
		def("initialize", &Game::initialize).
		def("start", &Game::start).
		def("showConsole", &Game::showConsole).
		def("setOnDrawEvent", &Game::setOnDrawEvent).
		def("keyPressed", (bool(Game::*)(char)) &Game::isKeyDown).
		def("keyPressed", (bool(Game::*)(const std::string&)) &Game::isKeyDown).
		def("mouseDown", &Game::isMouseDown).
		def("getMousePosition", &Game::getMousePosition).
		def("stop", &Game::stop)
	];

	luabind::globals(lua::State())["game"] = this;
}

#pragma warning(pop)